package com.wangwei.authoritySystem.common.utils;

import com.wangwei.authoritySystem.pojo.Department;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DeadlockLoserDataAccessException;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

//生成部门树
public class DepartmentTree {
    /**
     * 生成部门树
     * @param departmentList
     * @param pid
     * @return
     */
    public static List<Department> createDepartmentTree(List<Department> departmentList,Long pid){
        //创建集合保存部门信息
        List<Department> list = new ArrayList<Department>();
        //判断部门列表是否为空，如果不为空则使用部门列表，否则创建集合对象
        Optional.ofNullable(departmentList).orElse(new ArrayList<Department>())
                .stream().filter(item -> item!=null && item.getPid().equals(pid))
                .forEach(item ->{
                    //创建部门对象
                    Department department = new Department();
                    //复制属性

                    BeanUtils.copyProperties(item,department);
                    //递归生成子部门
                    List<Department> children = createDepartmentTree(departmentList, item.getId());
                    department.setChildren(children);
                    //部门对象添加到集合
                    list.add(department);
                });
        return list;
    }
}
